package com.yhgm.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.yhgm.constant.KapchaCode;
import com.yhgm.utils.IpUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class CaptchaController {

    // 模拟缓存
    @Resource
    private KapchaCode kapchaCode;
    @Resource
    private IpUtil ipUtil;


    /**
     * 给前端返回一个验证码图片
     */
    @GetMapping("/identifyImage")
    public void identifyImage(HttpServletRequest request, HttpServletResponse response){
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
        lineCaptcha.setGenerator(new RandomGenerator("0123456789", 4));
        // 验证码值
        String code = lineCaptcha.getCode();
        //System.out.println("验证码值：" + code);
        String codeId = ipUtil.getIpAddr(request);
        if (codeId==null||codeId.equals("")){
            return;
        }
        // 模拟把验证码的值存储到缓存(记得添加过期时间)
        kapchaCode.getCodes().put(codeId, code);
        //取消了日志的打印
        //System.out.println(codeId+" "+code);
        //转为用户登录操作，在userService进行存储
        // 输出到客户端
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            // 图形验证码写出，写出到流
            lineCaptcha.write(outputStream);
        } catch (Exception e) {
            System.out.println("图形验证码输出错误");
        }
    }

    /**
     * 给前端返回一个base64格式的图片，前端需要转换为图片
     */
    @GetMapping("/identifyImageBase64")
    public String identifyImageBase64() {
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
        // 验证码值
        String code = lineCaptcha.getCode();
        System.out.println("验证码值：" + code);
        // 验证码以base64的格式返回到客户端
        return lineCaptcha.getImageBase64Data();
    }


}
